package cn.five.stream.manager;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Build;
import android.util.Log;
import android.view.SurfaceHolder;

public class CameraInterface {
	private static final String TAG = "foxy";
	private Camera mCamera;
	private Camera.Parameters mParams;
	private boolean isPreviewing = false;
	private float mPreviwRate = -1f;
	private static CameraInterface mCameraInterface;
	int bufferLength;
	byte[] previewBuffer;
	private int mDefaultCameraID = -1;
	private int mFacing = 0;
	private int height=360;
	private int width=480;
	private int fps=25;
	
	
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	public int getWidth() {
		return width;
	}
	public void setWidth(int width) {
		this.width = width;
	}

	public interface CamOpenOverCallback{
		public void cameraHasOpened();
	}

	private CameraInterface(){

	}
	public static synchronized CameraInterface getInstance(){
		if(mCameraInterface == null){
			mCameraInterface = new CameraInterface();
		}
		return mCameraInterface;
	}
	/**打开Camera
	 * @param callback
	 */
	public synchronized boolean doOpenCamera(CamOpenOverCallback callback,int facing){
		 try
	        {
	            if(Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO)
	            {
	                int numberOfCameras = Camera.getNumberOfCameras();

	                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
	                for (int i = 0; i < numberOfCameras; i++) {
	                    Camera.getCameraInfo(i, cameraInfo);
	                    if (cameraInfo.facing == facing) {
	                        mDefaultCameraID = i;
	                        mFacing = facing;
	                    }
	                }
	            }
	            doStopCamera();
	            if(mCamera != null)
	            	mCamera.release();

	            if(mDefaultCameraID >= 0) {
	            	mCamera = Camera.open(mDefaultCameraID);
	            }
	            else {
	            	mCamera = Camera.open();
	                mFacing = Camera.CameraInfo.CAMERA_FACING_BACK; //default: back facing
	            }
	        }
	        catch(Exception e)
	        {
	            e.printStackTrace();
	            mCamera = null;
	            return false;
	        }
		Log.i(TAG, "Camera open....");
			return true;
	
	}
	
	/**使用Surfaceview开启预览
	 * @param holder
	 * @param previewRate
	 */
	public void doStartPreview(SurfaceHolder holder, float previewRate){
		Log.i(TAG, "doStartPreview...");
		if(isPreviewing){
			mCamera.stopPreview();
			return;
		}
		if(mCamera != null){
			try {
				mCamera.setPreviewDisplay(holder);
			} catch (IOException e) {
				e.printStackTrace();
			}
			//initCamera(previewRate);
		}
	}
	/**使用TextureView预览Camera
	 * @param surface
	 * @param previewRate
	 */
	public void doStartPreview(SurfaceTexture surface, float previewRate,PreviewCallback preview){
		Log.i(TAG, "doStartPreview...");
		if(isPreviewing){
			mCamera.stopPreview();
			return;
		}
		if(mCamera != null){
			try {
				mCamera.setPreviewTexture(surface);
			} catch (IOException e) {
				e.printStackTrace();
			}
			/*initCamera(previewRate, preview);*/
		}
		
	}

	/**
	 * 停止预览，释放Camera
	 */
	public void doStopCamera(){
		if(null != mCamera)
		{
			mCamera.setPreviewCallback(null);
			mCamera.stopPreview(); 
			isPreviewing = false; 
			mPreviwRate = -1f;
			mCamera.release();
			mCamera = null;     
		}
	}
	/**
	 * 拍照
	 */
	public void doTakePicture(){
		if(isPreviewing && (mCamera != null)){
			mCamera.takePicture(mShutterCallback, null, mJpegPictureCallback);
		}
	}
	public boolean isPreviewing(){
		return isPreviewing;
	}


	/*private void initCamera(float previewRate,PreviewCallback preview){
		if(mCamera != null){
			mParams = mCamera.getParameters();
			mParams.setPictureFormat(PixelFormat.JPEG);//设置拍照后存储的图片格式
			Size pictureSize = CamParaUtil.getInstance().getPropPictureSize(
					mParams.getSupportedPictureSizes(),previewRate, 600);
			mParams.setPictureSize(pictureSize.width, pictureSize.height);
			Size previewSize = CamParaUtil.getInstance().getPropPreviewSize(
					mParams.getSupportedPreviewSizes(), previewRate, 600);
			mParams.setPreviewSize(previewSize.width, previewSize.height);
			mParams.setPreviewFrameRate(fps);
			this.height=previewSize.height;
			this.width=previewSize.width;
			
//			previewSize.width=pictureSize.width;
//			previewSize.height=pictureSize.height;
			mParams.setPreviewFormat(ImageFormat.YV12);  
			int stride = (int) Math.ceil(previewSize.width/16.0f) * 16;
	    	int cStride = (int) Math.ceil(previewSize.width/32.0f)  * 16;
	        final int frameSize = stride * previewSize.height;
	        final int qFrameSize = cStride * previewSize.height / 2;
			
	        previewBuffer = new byte[frameSize + qFrameSize * 2];
	        bufferLength=frameSize + qFrameSize * 2;
		        mCamera.addCallbackBuffer(previewBuffer);
				mCamera.setPreviewCallbackWithBuffer(preview);
				
				if ("Nexus 6P".equals(android.os.Build.MODEL)) {
					mCamera.setDisplayOrientation(180);
				}
				
			//mCamera.setDisplayOrientation(270);
//			CamParaUtil.getInstance().printSupportFocusMode(mParams);
			List<String> focusModes = mParams.getSupportedFocusModes();
			if(focusModes.contains("continuous-video")){
				mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
			}
			mCamera.setParameters(mParams);	
			mCamera.startPreview();//开启预览

			isPreviewing = true;
			mPreviwRate = previewRate;
			mParams = mCamera.getParameters(); //重新get一次
			Log.i("size", "最终设置:PreviewSize--With = " + mParams.getPreviewSize().width                                                          
					+ "Height = " + mParams.getPreviewSize().height);
			Log.i("size", "最终设置:PictureSize--With = " + mParams.getPictureSize().width
					+ "Height = " + mParams.getPictureSize().height);
			
//			mCamera.stopPreview();
//			isPreviewing = false;
//		//	mCamera.setDisplayOrientation(90);
//			mCamera.startPreview();
//			isPreviewing=true;
		}
	}*/
	public void addCallbackBuffer(){
		mCamera.addCallbackBuffer(previewBuffer); 
	}



	/*为了实现拍照的快门声音及拍照保存照片需要下面三个回调变量*/
	ShutterCallback mShutterCallback = new ShutterCallback() 
	//快门按下的回调，在这里我们可以设置类似播放“咔嚓”声之类的操作。默认的就是咔嚓。
	{
		public void onShutter() {
			// TODO Auto-generated method stub
			Log.i(TAG, "myShutterCallback:onShutter...");
		}
	};
	PictureCallback mRawCallback = new PictureCallback() 
	// 拍摄的未压缩原数据的回调,可以为null
	{

		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			Log.i(TAG, "myRawCallback:onPictureTaken...");

		}
	};
	PictureCallback mJpegPictureCallback = new PictureCallback() 
	//对jpeg图像数据的回调,最重要的一个回调
	{
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			Log.i(TAG, "myJpegCallback:onPictureTaken...");
			Bitmap b = null;
			if(null != data){
				b = BitmapFactory.decodeByteArray(data, 0, data.length);//data是字节数据，将其解析成位图
				mCamera.stopPreview();
				isPreviewing = false;
			}
			//保存图片到sdcard
			if(null != b)
			{
				//设置FOCUS_MODE_CONTINUOUS_VIDEO)之后，myParam.set("rotation", 90)失效。
				//图片竟然不能旋转了，故这里要旋转下
//				Bitmap rotaBitmap = ImageUtil.getRotateBitmap(b, 90.0f);
//				FileUtil.saveBitmap(rotaBitmap);
			}
			//再次进入预览
			mCamera.startPreview();
			isPreviewing = true;
		}
	};
	/**
	 * 获取相机参数
	 * @return
	 */
	 public synchronized Camera.Parameters getParams() {
	        if(mCamera != null)
	            return mParams;
	        return null;
	    }
	 /**
	  * 设置相机参数
	  * @param param
	  */
	  public synchronized void setParams(Camera.Parameters param) {
	        if(mCamera != null) {
	            mParams = param;
	            mCamera.setParameters(mParams);
	        }
	    }
	 
	public void setCameraParams(int height,int width,int fps){
		this.height=height;
		this.width=width;
		this.fps=fps;
			
	}
	  
}
